I'm trying out Kotlin Serialization. After setting it up following the directions, I get the Unresolved reference: serializer build error with this code:
val serializer : KSerializer<User> = User.serializer()
I'm speculating that somehow the compiler plugin did not kick in, but can't see what I missed in the setup.
Here is my build.gradle.kts:
buildscript {
val kotlinVer: String by extra("1.3.20")
repositories { jcenter() }
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVer")
classpath("org.jetbrains.kotlin:kotlin-serialization:$kotlinVer")
}
}
plugins {
id("org.jetbrains.kotlin.jvm").version("1.3.20")
application
"kotlin"
"kotlinx-serialization"
}
repositories {
jcenter()
maven("https://kotlin.bintray.com/kotlinx")
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
compile("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.10.0")
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
application {
mainClassName = "com.digizen.AppKt"
}
In plugins, you can't just put a string as you did, the options are (for .kts):
plugins {
`«plugin id»` // (1)
id(«plugin id») // (2)
id(«plugin id») version «plugin version» [apply «false»] // (3)
}
I think the Kotlin plugin itself is activating because of id("org.jetbrains.kotlin.jvm").version("1.3.20"), not because of "kotlin".
The README says
Gradle (with plugins block)
You can setup serialization plugin with the kotlin plugin using Gradle plugins DSL instead of traditional apply plugin:
plugins { id 'kotlin-multiplatform' version '1.3.20' id 'kotlinx-serialization' version '1.3.20' }In this case, since serialization plugin is not published to Gradle plugin portal yet, you'll need to add plugin resolution rules to your settings.gradle:
pluginManagement { resolutionStrategy { eachPlugin { if (requested.id.id == "kotlin-multiplatform") { useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}") } if (requested.id.id == "kotlinx-serialization") { useModule("org.jetbrains.kotlin:kotlin-serialization:${requested.version}") } } } }Don't forget to drop classpath dependency on the plugin from the buildscript dependencies, otherwise, you'll get an error about conflicting versions.
So the least change would be to remove the two strings from plugins block and
add
apply plugin: 'kotlinx-serialization'
instead.
Android Kotlin Answer
Follow documentation: Serialization Adding for Android + Kotlin
Key point: (build.gradle - Module)
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2")
}